<?php

namespace app\admin\model;

use app\admin\model\user\Integral;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use think\Db;
use think\Model;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = '';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text'
    ];

    public function getOriginData()
    {
        return $this->origin;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double)$changedata['money'] !== (double)$origin['money'])) {
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
            if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
        });
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['prevtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['logintime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['jointime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function userIntegral($uid, $integral = 0, $time, $type,$is_type)
    {

        Db::startTrans();
        try{
            Integral::create([
                'uid' => $uid,
                'integral'    => $integral,
                'type'        => $type,
                'is_type'     => $is_type,
                'create_time' => $time
            ]);

            $user = self::get($uid);
            if ($is_type == 1)
            {
                $interNumber = (float)$user['score'] + (float)$integral;
            }else{
                $interNumber = (float)$user['score'] - (float)$integral;
            }
            $user->score = $interNumber;
            $user->save();
            $result = true;
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            var_dump($e->getMessage());
            $result = false;
        }

        return $result;

    }

    /**
     * @param $uid 用户id
     * @param $money 金额
     * @param string $type 获取渠道
     * @param $is_type 状态
     */
    public function userMoney($uid, $money, $type = '', $is_type)
    {
        try {
            $userInfo = self::get($uid);
            $time = time();
            if (!empty($userInfo))
            {
                if ($is_type == 1)
                {
                    $userInfo->money = $userInfo['money'] + $money;
                }else{

                }
                $userInfo->save();
                $moneyId = Db::name('user_money')->insertGetId([
                        'uid'   => $uid,
                        'money' => $money,
                        'type'  => $type,
                        'create_time' => $time,
                        'is_type'  => $is_type,
                    ]);
                $res = false;

                if ($userInfo->id && $moneyId)
                {
                    $res = true;
                    Db::commit();
                }

            }else{
                $res = false;
            }
        }catch(\Exception $e){
            echo $e->getMessage();
            Db::rollback();
            $res = false;
        }
        return $res;
    }

    public function vehicle()
    {
        return $this->belongsTo('Vehicle','models','id',[],'LEFT')->setEagerlyType(0);
    }


}
